package com.twxm.breed.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.twxm.breed.entity.User;
import com.twxm.breed.redis.ScanQrcodeRedis;
import com.twxm.breed.redis.WXRedis;
import com.twxm.breed.service.LoginInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
@Slf4j
public class WechatLoginController {


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    LoginInfoService loginInfoService;

    @Autowired
    ScanQrcodeRedis scanQrcodeRedis;

    @Autowired
    WXRedis wxRedis;

    /**
     *  当扫码之后微信会来调用的，/weixinlogin记得跟前端的回调url的最后面一样
     */
    @RequestMapping(value = "/weixinlogin")
    public String weixinlogin(HttpServletRequest request,
                              @RequestParam(value = "state") String state,
                              @RequestParam(value = "id") String id) {
        JSONObject jsonObject = new JSONObject();
        String code = request.getParameter("code");
        // 查看获取到的code
        log.info("进入微信登入方法，code为：{}, state为：{}",code,state);
        if (code == null || code.equals("") || scanQrcodeRedis.get(id) == null){
            return "wxLoginWrong";
        }
        // 根据code获取access_token和openId
        // 微信请求地址标准格式url
        String getAccessTokenAndOpenIdUrl="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ "wx2c34a76c56a55cc4"
                +"&secret="+"db5844fc81d66ce314081a4aeaf8732f"+"&code="+code+"&grant_type=authorization_code";

        // 向微信发送请求获取access_token与openid
        Map map = JSON.parseObject(restTemplate.getForObject(getAccessTokenAndOpenIdUrl, String.class), Map.class);

        // 开始遍历参数
        map.forEach(
                (key,value)->{
                    log.info("根据code请求微信获取的值，key：{}, value：{}",key,value);
                }
        );

        // 获取accessToken
        String access_token = map.get("access_token").toString();

        // 获取openid
        String openid = map.get("openid").toString();

        //标记扫码了
        scanQrcodeRedis.set(id, openid);

        //根据openid查询用户是否注册过
        String userId = loginInfoService.selectUserIdByOpenId(openid);
        if (userId == null || userId.equals("")){
            wxRedis.set(openid, "f");//没注册
        }else{
            wxRedis.set(openid, "t");
        }

        // 再次请求微信平台，获取用户信息
        String getUserInfoUrl="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";

        // 发起请求
        Map userInfoMap = JSON.parseObject(restTemplate.getForObject(getUserInfoUrl, String.class), Map.class);
        userInfoMap.forEach((key, value)-> {
            log.info("微信获取用户信息，key为：{}, value为：{}",key,value);
        });
        // 把当前用户信息返回
//        return JSON.toJSONString(userInfoMap);
        return "wxLoginSuccess";
    }

}

